package com.bigegg.employee.api;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.bigegg.employee.domain.EncodeSignInBody;
import com.bigegg.employee.domain.RegisterInfo;
import com.bigegg.employee.domain.SignInBody;
import com.bigegg.employee.domain.TokenWrap;
import com.bigegg.employee.service.impl.CLoginService;
import com.bigegg.employee.service.impl.CUserService;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;


/**
 * 通用 API
 *
 * @author sun
 */
@RestController
@RequestMapping("/api/")
public class CommonApi {

    private final Logger logger = LoggerFactory.getLogger(CommonApi.class);


    @Autowired
    CLoginService cLoginService;

    @Autowired
    TokenService tokenService;


    @Autowired
    CUserService cUserService;


    // 登录
    @PostMapping("/login")
    public AjaxResult doLogin(@RequestBody EncodeSignInBody encodeSignInBody) {

        SignInBody signInBody = encodeSignInBody.getSignInBody();
        logger.info("用户名：{}， 密码： {}", signInBody.getUsername(), signInBody.getPwd());
        TokenWrap token = cLoginService.login(signInBody.getUsername(), signInBody.getPwd());
        return AjaxResult.success(token);
    }

    // 登出
    @RequestMapping("/quit")
    public void doLogout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {//清除认证
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
    }

    // 检查token是否有效
    @PostMapping("/check_token")
    public AjaxResult checkToken(HttpServletRequest request) {
        LoginUser user = tokenService.getLoginUser(request);
        return user == null ? AjaxResult.error() : AjaxResult.success();
    }

    // 获取用户基本信息
    @PostMapping("/user_info")
    public AjaxResult getUserInfo(HttpServletRequest request, @RequestBody HashMap<String, Long> o) {
        Long sid = o.get("sid");
        if (sid == null) {
            LoginUser user = tokenService.getLoginUser(request);
            return AjaxResult.success(cUserService.getUserInfo(user));
        } else {
            return AjaxResult.success(cUserService.getUserInfo(sid, 2));
        }
    }


    /**
     * 注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestParam int type, @RequestBody RegisterInfo registerInfo) {

        cUserService.registerTypeUser(type, registerInfo);
        return AjaxResult.success();
    }
}
